package com.fanhang.samples.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class InsertGeneratedKeys {

	private static final ConnectionProvider connectionProvider = ConnectionProvider.getInstance();
	
	/**
	 * 使用Statement.RETURN_GENERATED_KEYS 指定返回生成主键
	 */
	public static void main(String[] args) {

		PreparedStatement pst = null;
		ResultSet rs = null;
		Connection conn = null;
		try {
			conn = connectionProvider.getConnection();
		} catch (Exception e1) {
			System.exit(-1);
		}
		
		String sql = "insert into test(id,name) values(?,?)";
		try {
			// String generatedColumns[] = { "ID" }; //获得指定ID
			pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); // 指定返回生成的主键
			pst.setString(1, "123x");
			pst.setString(2, "test");
			int ii = pst.executeUpdate();

			// 检索对象生成的键
			rs = pst.getGeneratedKeys();
			if (rs.next()) {
				System.out.println("数据主键：" + rs.getString(1));
			}
			connectionProvider.closeConnection();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
